#include <cstdlib>
#include <ctime>
#include <cstring>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include "TcpService.h"

TcpService::TcpService()
{
	if (randSeed == 0) {
		srand(time(NULL));
		randSeed = 1;
	}
	tcpSocket = socket(PF_INET, SOCK_STREAM, 0);
	bzero(&tcpAddr, addr_len);
	tcpAddr.sin_family = AF_INET;
	return;
}

int TcpService::createService(std::string ip, int maxconn)
{
	int port = 20000 + rand() % 30000;
	return createService(ip, port, maxconn);
}

int TcpService::createService(std::string ip, int port, int maxconn)
{
	tcpAddr.sin_port = htons(port);
	inet_aton(ip.c_str(), &tcpAddr.sin_addr);
	bind(tcpSocket, (struct sockaddr *) &tcpAddr, addr_len);	
	listen(tcpSocket, maxconn);
	return port;
}

int TcpService::acceptConnection()
{
	return accept(tcpSocket, (struct sockaddr *) &tcpAddr,
			&addr_len);
}

void TcpService::connectToService(std::string ip, int port)
{
	tcpAddr.sin_port = htons(port);
	inet_aton(ip.c_str(), &tcpAddr.sin_addr);
	connect(tcpSocket, (struct sockaddr *) &tcpAddr,
			addr_len);
	return;
}

void TcpService::closeService()
{
	close(tcpSocket);
	return;
}

ssize_t TcpService::TcpSend(void *buf, size_t len)
{
	return send(tcpSocket, buf, len, 0);
}

ssize_t TcpService::TcpRecv(void *buf, size_t len)
{
	return recv(tcpSocket, buf, len, 0);
}

int TcpService::randSeed = 0;
socklen_t TcpService::addr_len = sizeof(struct sockaddr_in);
